package by.scsbsu.database.dao;

import by.scsbsu.database.bean.TaskAttach;
import by.scsbsu.database.tools.DbConnectionPool;

public class TaskAttachDAO extends AbstractDAO {
	public static final String SQL_TASK_ATTACH_CREATE_TASK_ATTACH = "INSERT INTO task_attach ( id_task , name , status , id_user ) VALUES ( ? , ? , ? , ?);";
	public static final String SQL_TASK_ATTACH_GET_ID_CREATE_TASK_ATTACH = "SELECT id FROM task_attach WHERE ( ( id_task = ? ) AND ( id_user = ? ) );";
	public static final String SQL_TASK_ATTACH_UPDATE_NAME = "UPDATE task_attach SET ( name = ? ) WHERE ( id = ? );";
	public static final String SQL_TASK_ATTACH_UPDATE_STATUS = "UPDATE task_attach SET ( status = ? ) WHERE ( id = ? );";
	public static final String SQL_TASK_ATTACH_DELETE_TASK_ATTACH_BY_ID = "DELETE FROM task_attach WHERE ( id = ? );";
	
	public TaskAttach createTaskAttach(TaskAttach taskAttach){
		try {
			connection = DbConnectionPool.getConnection();
			
			statement = connection.prepareStatement(SQL_TASK_ATTACH_CREATE_TASK_ATTACH);
			statement.setInt(1, taskAttach.getIdTask());
			statement.setString(2, taskAttach.getName());
			statement.setString(3, taskAttach.getStatus());
			statement.setInt(4, taskAttach.getIdUser());
			statement.executeUpdate();
			
			statement = connection.prepareStatement(SQL_TASK_ATTACH_GET_ID_CREATE_TASK_ATTACH);
			statement.setInt(1, taskAttach.getIdTask());
			statement.setInt(4, taskAttach.getIdUser());
			
			resultSet = statement.executeQuery();
			if(resultSet.next()){
				taskAttach.setId(resultSet.getInt("id"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close();
		}
		return taskAttach;
	}
	
	public void updateName(int id, String name){
		try {
			connection = DbConnectionPool.getConnection();
			
			statement = connection.prepareStatement(SQL_TASK_ATTACH_UPDATE_NAME);
			statement.setString(1, name);
			statement.setInt(2, id);
			statement.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close();
		}
	}
	
	public void updateStatus(int id, String status){
		try {
			connection = DbConnectionPool.getConnection();
			
			statement = connection.prepareStatement(SQL_TASK_ATTACH_UPDATE_STATUS);
			statement.setString(1, status);
			statement.setInt(2, id);
			statement.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close();
		}
	}
	
	public void deleteTaskAttachById(int id){
		try {
			connection = DbConnectionPool.getConnection();
			
			statement = connection.prepareStatement(SQL_TASK_ATTACH_DELETE_TASK_ATTACH_BY_ID);
			statement.setInt(1, id);
			statement.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close();
		}
	}
}
